"use strict";

(function() {
	var BOUNDS_PADDING = 2;
	
	alx.lj.Selectable = function (args) {
		var me = this;
		
		var _pp       = null,
				_elem     = args.elem,
				_canvas   = args.canvas,
				_rect     = null,
				_hit      = false,
				_document = null;
				
				
		me.init = function() {
			_pp = getPhysicalProps(_elem);
			_document = me.getRootDocument();
		};
		
		me.showSelectionRect = function (canvas) {
			_canvas = canvas;
			if (!_rect || !_rect.parentNode) _createRect();
				
			if (_rect) _rect.setAttribute("visibility", "visible");
		};
		
		me.hideSelectionRect = function (canvas) {
			if (_rect) _rect.setAttribute("visibility", "hidden");
		};
		
		me.setHit = function () { _hit = true; };
		me.isHit = function () { return _hit; };
		
		me.getHref = function () { return _elem.getAttribute("href"); };
		
		me.hitTest = function (x, y) {
			if ((x >= _pp.left && x <= _pp.left + _pp.width) && (y >= _pp.top && y <= _pp.top + _pp.height)) {
				return true;
			}
			
			return false;
		};
		
		me.getRootDocument = function () {
			var obj = _elem;
			
			while (obj && obj.nodeType != 9) {
				obj = obj.parentNode;
			}
			
			return obj;
		};
		
		me.getBounds = function () {
			var totalOffsetTop = 0,
			totalOffsetLeft = 0,
			current = _elem;
	
			while (current != null) {
				totalOffsetTop += current.offsetTop;
				totalOffsetLeft += current.offsetLeft;
				
				current = current.offsetParent;
			}
					
			return { 
					top:    totalOffsetTop    - BOUNDS_PADDING, 
					left:   totalOffsetLeft   - BOUNDS_PADDING,
					bottom: totalOffsetTop + _elem.offsetHeight + BOUNDS_PADDING,
					right:  totalOffsetLeft + _elem.offsetWidth + BOUNDS_PADDING
			};
		};
		
		// Private stuff
		
		var getPhysicalProps = function(elem) { 
			var totalOffsetTop = 0,
					totalOffsetLeft = 0,
					current = elem;
			
			while (current != null) {
				totalOffsetTop += current.offsetTop;
				totalOffsetLeft += current.offsetLeft;
				
				current = current.offsetParent;
			}
					
			return { 
					top:    totalOffsetTop, 
					left:   totalOffsetLeft,
					width:  elem.offsetWidth,
					height: elem.offsetHeight
			};
		};
		
		var _createRect = function () {
			_rect = _document.createElementNS(alx.svg.ns, "rect");
			
			var props = {
				"x":      _pp.left,
				"y":      _pp.top,
				"width":  _pp.width,
				"height": _pp.height,
				"fill":   "#3399ff",
				"fill-opacity": 0.1,
				"shape-rendering":  "crispEdges",
				"stroke":          "#3399ff",
				"stroke-lineJoin": "round",
				"stroke-width": 1
			};
			
			alx.svg.setAttributeMap(props, _rect);
			_canvas.getElement().appendChild(_rect);
		};
	
		
		// ---------- //
		me.init();
	};
})();